package com.eric.enderslastgame.threads;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

import com.eric.enderslastgame.EndersGamePanel;

public class RepaintThread extends Thread {

	private static final String TAG = BugGenThread.class.getSimpleName();

	// Surface holder that can access the physical surface
	private SurfaceHolder surfaceHolder;
	// The actual view that handles inputs
	// and draws to the surface
	private EndersGamePanel gamePanel;

	public RepaintThread(SurfaceHolder surfaceHolder, EndersGamePanel gamePanel) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.gamePanel = gamePanel;
	}

	@Override
	public void run() {
		while (EndersGamePanel.inGame) {
			Canvas canvas;
			Log.d(TAG, "Starting repaint thread");
			while (EndersGamePanel.inGame) {
				canvas = null;
				// try locking the canvas for exclusive pixel editing
				// in the surface
				try {
					canvas = this.surfaceHolder.lockCanvas();
					synchronized (surfaceHolder) {
						// render state to the screen
						// draws the canvas on the panel
						gamePanel.render(canvas);				
					}
				} finally {
					// in case of an exception the surface is not left in 
					// an inconsistent state
					if (canvas != null) {
						surfaceHolder.unlockCanvasAndPost(canvas);
					}
				}
			}
		}
	}
}
